<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2018/11/22
 * Time: 下午5:52
 */

namespace Common\Service;

use Api\Service\UserService;
use Mobile\Controller\WechatController;

class WechatService extends BaseService
{

    public $wechat;
    public function __construct()
    {
        $this->wechat=new WechatController();
    }

    public function codeBackUserInfo($code){
        if(empty($code)){
            return array('code'=>202,'msg'=>'code为空');
        }
        $wechat=new WechatController(array());
        $wechatuserInfo =$wechat->getOauthAccessByApp($code) ;
        if(!$wechatuserInfo['openid']){
           return array('code'=>202,'msg'=>'微信用户信息未查询');
        }
        $where['openid']=$wechatuserInfo['openid'];
        $userInfo=UserService::S()->findUserInfo($where);
        if(!$userInfo){
            $add=self::_get_user_info($wechatuserInfo);
            $add['uid']=UserService::S()->add($add);
            return array('code'=>200,'msg'=>'success','data'=>$add);
        }else{
            return array('code'=>200,'msg'=>'success','data'=>$userInfo);
        }
    }

    /*
	 * 从接口获取用户的最新信息
	 */
    public function _get_user_info($access_token){
        //请求网址授权接口
        $wxuser = $this->wechat->getOauthUserinfo($access_token['access_token'],$access_token['openid']);//获取授权用户细信息
        //$wxuser = $this->wechat->getUserInfo($access_token['openid']);//获取关注者信息
        if(empty($wxuser)){
            $wxuser = $this->wechat->getOauthUserinfo($access_token['access_token'],$access_token['openid']);//获取授权用户细信息
            if(empty($wxuser)){
                return false;
            }
        }
        $params = array(
            "openid","headimgurl","unionid","sex","province","city","country","privilege","groupid","language","remark","nickname","subscribe"
        );
        $user_data = getParmas($wxuser,$params);//获取含有的参数
        //昵称非主流乱码过滤
        if(isset($wxuser['nickname'])){
            $user_data['nickname'] = str_replace(array(",","'","\"","\\","\/","`"),array("，","＂","＂","","",""),$wxuser['nickname']);//转义
            $user_data['nickname'] = str_replace(PHP_EOL, '', $wxuser['nickname']);  //去除换行符号
        }
        //关注时间
        $subscribe_time = set_default($wxuser,"subscribe_time");
        if($subscribe_time){
            $user_data['subscribe_time'] = date("Y-m-d H:i:s",$subscribe_time);
        }

        return $user_data;
    }


}